const { app, BrowserWindow,screen,ipcMain } = require('electron');
const Store = require('electron-store');
const path = require('path');
const {dialog} = require('electron');
const fs = require('fs');
const Papa = require('papaparse');
// const iconv = require('iconv-lite');
// const chardet = require('chardet');

let savePreFilePath = undefined;
// let readPreFilePath = undefined;


// Handle creating/removing shortcuts on Windows when installing/uninstalling.
if (require('electron-squirrel-startup')) {
  app.quit();
}
// const store = new Store({
//   // cwd:app.getAppPath(),
//   // name:'localStore',
// });
const store = new Store();
const createWindow = () => {
  // Create the browser window.
  const { width, height } = screen.getPrimaryDisplay().bounds; 
  const mainWindow = new BrowserWindow({
    width,
    height,
    webPreferences: {
      preload: path.join(__dirname, 'preload.js'),
    },
  });
  //store的接口
  ipcMain.on('electron-store-get', async (event, val) => {
      event.returnValue = store.get(val);
  });
  ipcMain.on('electron-store-set', async (event, key, val) => {
    store.set(key, val);
  });
  ipcMain.on('electron-store-path', async (event) => {
      event.returnValue = store.path;
  });
  //创建新的窗口
  ipcMain.on('open-window', async (event, url) => {
    const { width, height } = screen.getPrimaryDisplay().bounds; 
    const newWindow = new BrowserWindow({
      width,
      height,
      webPreferences: {
        preload: path.join(__dirname, 'preload.js'),
      },
    });
    newWindow.loadFile(path.join(__dirname, `index.html`),{hash:url});
    newWindow.setMenuBarVisibility(false);
    // newWindow.webContents.openDevTools();
  });
  //读取csv
  ipcMain.handle('electron-get-csv', async() =>{  
    let { canceled, filePaths } = await dialog.showOpenDialog({
      title: "请选择csv文件",
      filters: [{name:'CSV', extensions: ['csv'] }]
    })
    let csvFile;
    if(!canceled && filePaths[0]){
      let path = filePaths[0];
      csvFile = fs.readFileSync(path, 'utf-8');
      csvFile = Papa.parse(csvFile, { header: true });
    }

    return {canceled,filePaths,csvFile};
  });
  //保存文件
  ipcMain.on('save-file',async (event,{data,fileName,filters}) => {
      if(typeof data != 'string'){
        data = JSON.stringify(data);
      }
      let prePath = savePreFilePath || app.getAppPath();
      let{canceled,filePath} = await dialog.showSaveDialog({
        title:'导出',
        defaultPath: path.join(prePath,`${fileName}.json`),
        buttonLabel:"确认",
        filters,
      });
      if(!canceled && filePath){
        let {dir} = path.parse(filePath);
        savePreFilePath = dir;
        fs.writeFileSync(filePath,data);
      }
  })
  //读取文件
  ipcMain.handle('read-file',async (event,filters,multiSelections) => {
    // multiSelections = true;
    let properties = [];
    if(multiSelections) properties.push('multiSelections');
    let { canceled, filePaths } = await dialog.showOpenDialog({
      title: "请选择文件",
      filters: filters,
      properties,
    })
    let fileContents = [];
    if(!canceled && filePaths && filePaths.length > 0){
      filePaths.forEach(filePath => {
        let content = fs.readFileSync(filePath,'utf-8');
        content = JSON.parse(content);
        fileContents.push({filePath,content});
      })
    }
    return ({canceled,fileContents})
  })
  // and load the index.html of the app.
  mainWindow.loadFile(path.join(__dirname, 'index.html'));
  // mainWindow.loadURL('http://bosstv.utvgo.com:9999/tenxun_service/');

  // Open the DevTools.
  // mainWindow.webContents.openDevTools();
  mainWindow.setMenuBarVisibility(false);
  // mainWindow.setTitleBarColor('#151517');
};

// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.on('ready', createWindow);

// Quit when all windows are closed, except on macOS. There, it's common
// for applications and their menu bar to stay active until the user quits
// explicitly with Cmd + Q.
app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    app.quit();
  }
});

app.on('activate', () => {
  // On OS X it's common to re-create a window in the app when the
  // dock icon is clicked and there are no other windows open.
  if (BrowserWindow.getAllWindows().length === 0) {
    createWindow();
  }
});

// In this file you can include the rest of your app's specific main process
// code. You can also put them in separate files and import them here.
